package com.elastic.op;

import com.elastic.mapping.ClientFactory;
import com.elastic.mapping.createIndexWithMapping;
import com.elastic.util.DateUtil;
import com.elastic.util.EsUtil;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;

import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class OpAction {
	static class Kw{
		private Long id;
		private String kw;
		private Date edate;
		private Boolean flag;

		public Boolean getFlag() {
			return flag;
		}

		public void setFlag(Boolean flag) {
			this.flag = flag;
		}

		public Long getId() {
			return id;
		}
		public void setId(Long id) {
			this.id = id;
		}
		public String getKw() {
			return kw;
		}
		public void setKw(String kw) {
			this.kw = kw;
		}
		public Date getEdate() {
			return edate;
		}
		public void setEdate(Date edate) {
			this.edate = edate;
		}
		
		public Kw(Long id, String kw, Date edate) {
			super();
			this.id = id;
			this.kw = kw;
			this.edate = edate;
		}
		
	}
	
	//int 不能直接和Long 转换 Long.valuesof
	public static void addKwData(String index,String type){
		for(int i=1;i<100;i++){
			try {
				Date d = DateUtil.convertStringToDate(DateUtil.YYYY_MM_DD_HH_MM_SS,"2015-06-10  11:20:30");
				Kw w = null;
				w= new Kw(Long.valueOf(String.valueOf(i)),"kw:"+i,d);
				if(i == 2){
					w.setFlag(false);
				}else if(i == 3){
					w.setFlag(true);
				}
			     IndexResponse response = ClientFactory.getInstance().prepareIndex(index, type, String.valueOf(i))
				 .setSource(addKwJsonData(w,i)).execute().actionGet();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	public static void addSortCompartTable(String index,String type)throws Exception{
		Date d = DateUtil.convertStringToDate(DateUtil.YYYY_MM_DD_HH_MM_SS,"2015-06-10  11:20:30");
		Kw w = new Kw(Long.valueOf(1),"kw:1",d);
		IndexResponse response = ClientFactory.getInstance().prepareIndex(index, type)
				.setSource(addKwJsonDataIdStr(w)).execute().actionGet();
	}
	
	/**
	 测试elasticsearch Id 如果是相同的问题，添加的时候，后面会覆盖前面的数据问题吗?
	  测试结果: 第2 条会把第1条结果给覆盖,(因为文档的Id 第2次和第1次都是相同的都是null) 
	  因为，如果prepareIndex 如果你自己添加了id 的话，elasticsearch 会根据你给的id,生成文档Id, 后面的会把前面的覆盖。
	 * @param index
	 * @param type
	 */
	public static void testAddElasticSearchIdFugai(String index,String type){
		Date d = null;
		try {
			d = DateUtil.convertStringToDate(DateUtil.YYYY_MM_DD_HH_MM_SS,"2015-06-10  11:20:30");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		  Kw w = new Kw(null,"kw,ww,123,456",d);
	      IndexResponse response = ClientFactory.getInstance().prepareIndex(index, type, String.valueOf(w.getId()))
			.setSource(addKwJsonData(w,1)).execute().actionGet();
	      
	      w = new Kw(null,"xiaocai",d);
	        response = ClientFactory.getInstance().prepareIndex(index, type,String.valueOf(w.getId()))
	   			.setSource(addKwJsonData(w)).execute().actionGet();
	        System.out.println("2222");
	}

	/**
	 * 转换成json对象 json=={"id":"1","name":"aa","age":"20"}
	 * @return
	 */
	private static String addKwJsonData(Kw kw,int i ) {
		String json = "";
		try {
			XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
					.startObject();
			//			if("1".equals(kw.getId().toString())){
			//				contentBuilder.field("id", kw.getId());
			//			}else{
			//				contentBuilder.field("id","kw:"+kw.getId());
			//			}
			contentBuilder.field("id", kw.getId());
			contentBuilder.field("kw", kw.getKw());
			contentBuilder.field("userId",kw.getId());
			String uuid =  UUID.randomUUID().toString().replaceAll("-","");
			System.out.println("uuid:" + uuid);
			contentBuilder.field("userUuid", uuid);
			if(i != 1){
				contentBuilder.field("flag", kw.getFlag());
			}
			contentBuilder.field("edate",kw.getEdate().getTime());
			json = contentBuilder.endObject().string();
			System.out.println("json==" + json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}
	
	/**
	 * 转换成json对象 json=={"id":"1","name":"aa","age":"20"}
	 * 
	 * @param kw
	 * @return
	 */
	private static String addKwJsonData(Kw kw) {
		String json = "";
		try {
			XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
					.startObject();
//			if("1".equals(kw.getId().toString())){
//				contentBuilder.field("id", kw.getId());
//			}else{
//				contentBuilder.field("id","kw:"+kw.getId());
//			}
			contentBuilder.field("id", kw.getId());
			contentBuilder.field("kw", kw.getKw());
			contentBuilder.field("userId",kw.getId());
			String uuid =  UUID.randomUUID().toString().replaceAll("-","");
			System.out.println("uuid:" + uuid);
			contentBuilder.field("userUuid", uuid);
			contentBuilder.field("edate",kw.getEdate().getTime());
			json = contentBuilder.endObject().string();
			System.out.println("json==" + json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	private static String addKwJsonDataIdStr(Kw kw) {
		String json = "";
		try {
			XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
					.startObject();
			contentBuilder.field("id", Long.valueOf(kw.getId()));
			contentBuilder.field("kw", kw.getKw());
			contentBuilder.field("edate",kw.getEdate().getTime());
			json = contentBuilder.endObject().string();
			System.out.println("json==" + json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}


	public static void main(String[] args) throws Exception {
		//Date date = new Date();
		//System.out.println(date);
		//createIndexWithMapping.updateMapping(createIndexWithMapping.indexName, createIndexWithMapping.tableArr[1]);
		//createIndexWithMapping.deleteMapping(createIndexWithMapping.indexName,createIndexWithMapping.tableArr[1]);
		//initData();

		//addSortCompartTable(createIndexWithMapping.indexName, createIndexWithMapping.tableArr[0]);
		search(createIndexWithMapping.indexName, createIndexWithMapping.tableArr[1]);

		  //SearchRequestBuilder searchBuilder =ClientFactory.getInstanceRemote().prepareSearch("fxtweb_ruiyang");//指定多个数据库
		  // searchBuilder.setTypes("customer");
		   //ClientFactory.getInstanceRemote().prepareCount(indices)
	  	  // System.out.println(searchRecordListCount(searchBuilder));
	  	
	  	 //searchRemote("fxtweb_ruiyang","customer");

	}

	public static void initIndex(){
		createIndexWithMapping.createIndex(createIndexWithMapping.indexName);
		try {
			createIndexWithMapping.createMapping(createIndexWithMapping.indexName, createIndexWithMapping.tableArr[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void initData(){
		try {
		  addKwData(createIndexWithMapping.indexName, createIndexWithMapping.tableArr[1]);
		  //testAddElasticSearchIdFugai(createIndexWithMapping.indexName2,createIndexWithMapping.tableArr[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 
	 * wildcardQuery 模糊搜索 *ss*
	 * totalCount==5,a==10,b==10
	 * hits.total —— 能够匹配我们查询标准的文档的总数目
     - hits.hits —— 真正的搜索结果数据（默认只显示前10个文档）
     
	 * must 和should 满足一个就行了
     * QueryBuilder qb = boolQuery()
	    .must(QueryBuilders.termQuery("id", "11"))
	    .should(termQuery("id","100"))
	    ;
	    uuid 字符串会默认分词，-

	    如果有一个字段存在true,
	   mustNot 如果字段为false,或者这行不存在这个字段，那么也会满足情况；
	 */
	public static void search(String indexKey,String type){
		   SearchRequestBuilder searchBuilder = ClientFactory.getInstance().prepareSearch(indexKey);//指定多个数据库
		   searchBuilder.setTypes(type);
		   searchBuilder.addSort("id", SortOrder.ASC);
		
		   QueryBuilder qb = QueryBuilders.boolQuery()
				    .must(QueryBuilders.termQuery("id", "2"))
				   .mustNot(QueryBuilders.termQuery("flag", true));//flag不存在字段和为false 都满足情况， 和true的情况

//				    ; 
//		   QueryBuilder  qb = boolQuery().must(QueryBuilders.wildcardQuery("id",  "11"));
//	     	QueryBuilder qb = QueryBuilders.termsQuery("userId","1");
//		   QueryBuilder qb = QueryBuilders.termsQuery("id","11");
		   queryFiled(searchBuilder,qb);
	}
	
	//213
	private static void queryAll(SearchRequestBuilder  searchBuilder,QueryBuilder  qb){
		SearchResponse searchResponse = searchBuilder/*.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)*/
			       .setQuery(qb)// Query
			        //后面的条件query 会把前面的query 给覆盖掉。*
			        //.setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18))   // Filter
			       // .setPostFilter(QueryFilter.testBoolFilter())
			        .setFrom(0).setSize(5).setExplain(true)
			        .execute()
			        .actionGet();
	    SearchHits hits = searchResponse.getHits();
	    long totalCount = hits.getHits().length;
	    long a = hits.totalHits();//总数
	    long b = hits.getTotalHits();//shangmxiagntong 
		 for (int i = 0; i < totalCount; i++) {
	    	 Map<String,Object> map = hits.getAt(i).getSource();
	    	 //System.out.println("map=="+map);
	    	 //System.out.println("map=="+map);
	    	 //EsUtil.printMapFiled(map);
    }
	}
	
	
	//249
	private static void queryFiled(SearchRequestBuilder  searchBuilder,QueryBuilder  qb){
		SearchResponse searchResponse = searchBuilder
				  /*.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)*/
			       .setQuery(qb)// Query
			        //后面的条件query 会把前面的query 给覆盖掉。*
			        //.setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18))   // Filter
			       // .setPostFilter(QueryFilter.testBoolFilter())
			        //.addFields("id","edate")
			        .setFrom(0).setSize(5).setExplain(true)
			        .execute()
			        .actionGet();
				   getSomeField(searchResponse);
	}
	
	
	private static void getSomeField(SearchResponse searchResponse){
		//System.out.println("searchResponse =="+searchResponse);
	    SearchHits hits = searchResponse.getHits();
	    long totalCount = hits.getHits().length;
	    long a = hits.totalHits();//总数
	    long b = hits.getTotalHits();//shangmxiagntong
		System.out.println("totaolCount:"+totalCount+",a:+a"+",b:"+b);
	    for (int i = 0; i < totalCount; i++) {
			 System.out.println("sds:" + hits.getAt(i).getSourceAsString());
;	    	 Map<String,SearchHitField> map = hits.getAt(i).getFields();
	    	 //System.out.println("map=="+map);
	    	 //System.out.println("map=="+map);
	    	 //EsUtil.printMapFiled(map);
	    }
	}
	
	/**
	 * totalCount: 10 条 分页查询的结果的总数
	 * totalHits，getTotalHits 查询总结果总数
	 * @param searchResponse
	 */
	private static void getAllField(SearchResponse searchResponse){
		System.out.println("searchResponse =="+searchResponse);
	    SearchHits hits = searchResponse.getHits();
        long totalCount = hits.getHits().length;
        long a = hits.totalHits();//总数
        long b = hits.getTotalHits();//shangmxiagntong 
        System.out.println("totalCount=="+totalCount+",a=="+a +",b=="+b);
//        for (int i = 0; i < totalCount; i++) {
//        	 Map<String,Object> map = hits.getAt(i).getSource();
//        	 EsUtil.printMap(map);
//        }
	}
	
	
	 /**
     * 查询记录条数
     *
     * @param searchBuilder 过滤条件
     * @return long
     */
    public static long searchRemoteRecordListCount(SearchRequestBuilder searchBuilder) {
        long count = 0;
        SearchHits hits = null;
        try {
            long start = new Date().getTime();
            SearchResponse searchResponse = searchBuilder
                    .setSearchType(SearchType.COUNT).setExplain(false)
                    .execute()
                    .actionGet();
            hits = searchResponse.getHits();
            long end = new Date().getTime();
           System.out.println("SearchRecordUtil_searchRecordListCount:查询总数耗时：" + (end - start) + "ms");
            count = hits.totalHits();
        } catch (Exception e) {
            
        }
        return count;
    }

    
    public static void searchRemoteList(String indexKey,String type){
		   SearchRequestBuilder searchBuilder = ClientFactory.getInstanceRemote().prepareSearch(indexKey);//指定多个数据库
		   searchBuilder.setTypes(type);
		
//		   QueryBuilder qb = boolQuery()
//				    .must(termQuery("customerId", "298641")).; 
		   
		   SearchResponse searchResponse = searchBuilder/*.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)*/
	       // .setQuery(qb)// Query
	        //后面的条件query 会把前面的query 给覆盖掉。
	        //.setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18))   // Filter
				   .setFrom(0).setSize(60).setExplain(true)
	        .execute()
	        .actionGet();
		   
		    System.out.println("searchResponse =="+searchResponse);
		    SearchHits hits = searchResponse.getHits();
	        long totalCount = hits.getHits().length;
	        long a = hits.totalHits();//总数
	        System.out.println("totalCount=="+totalCount+",a=="+a);
	        for (int i = 0; i < totalCount; i++) {
	        	 Map<String,Object> map = hits.getAt(i).getSource();
	        	 EsUtil.printMap(map);
	        }
	}
    
    //删除mapping 的会删除数据吗？
    
   
    
}
